import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Button, message, Form, Input, Modal, Select, Icon, Upload, DatePicker } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import moment from 'moment';
import { faleUrl } from '../../../services/setting';
import information from '../../../utils/message';
import styles from './list.less';

const imgUpdate = `${faleUrl}/maps/v1/common/upload/attach`;

const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const confirm = Modal.confirm;
const Option = Select.Option;
const { TextArea } = Input;

function beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPG) {
        message.error('请上传JPG/PNG格式');
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
        message.error('上传大小限制为5MB');
    }
    return isJPG && isLt2M;
}

const CreateForm = Form.create()((props) => {
    const { modalVisible, form, handleAdd, handleModalVisible, townBer, loading, indexUpdate } = props;
    let { imageUrlBase } = props;
    if (imageUrlBase === '') imageUrlBase = townBer.sjTupian;
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            if (typeof (fieldsValue.sjTupian) !== 'undefined') {
                if (typeof (fieldsValue.sjTupian.file.response) !== 'undefined') {
                    prime.sjTupian = fieldsValue.sjTupian.file.response.data.path;
                } else {
                    delete prime.sjTupian;
                }
            }
            handleAdd(prime, townBer.id);
            form.resetFields();
        });
    };
    const canaleModal = () => {
        handleModalVisible();
        form.resetFields();
    };
    const uploadButton = (
        <div>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className="ant-upload-text">Upload</div>
        </div>
    );
    return (
        <Modal
            title="编辑"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={canaleModal}
            width={1100}
        >
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={12} sm={24}>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="报备名称"
                    >
                        {form.getFieldDecorator('name', {
                            rules: [{ required: true, message: '请输入报备名称' }],
                            initialValue: townBer.name,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="建新区地块号"
                    >
                        {form.getFieldDecorator('jxqNumber', {
                            rules: [{ required: true, message: '请输入建新区地块号' }],
                            initialValue: townBer.jxqNumber,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="土地坐落"
                    >
                        {form.getFieldDecorator('address', {
                            rules: [{ required: true, message: '请输入土地坐落' }],
                            initialValue: townBer.address,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="面积(公顷)"
                    >
                        {form.getFieldDecorator('areaGq', {
                            rules: [{ required: true, message: '请输入面积(公顷)' }],
                            initialValue: townBer.areaGq,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="面积(亩)"
                    >
                        {form.getFieldDecorator('areaM', {
                            rules: [{ required: true, message: '请输入面积(亩)' }],
                            initialValue: townBer.areaM,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="征地面积(公顷)"
                    >
                        {form.getFieldDecorator('areaZdGq', {
                            rules: [{ required: true, message: '请输入征地面积(公顷)' }],
                            initialValue: townBer.areaZdGq,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="备注"
                    >
                        {form.getFieldDecorator('remarks', {
                            rules: [{ required: true, message: '请输入备注' }],
                            initialValue: townBer.remarks,
                        })(
                            <TextArea placeholder="请输入" rows={4} />
                        )}
                    </FormItem>
                </Col>
                <Col md={12} sm={24}>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="征地面积(亩)"
                    >
                        {form.getFieldDecorator('areaZdM', {
                            rules: [{ required: true, message: '征地面积(亩)' }],
                            initialValue: townBer.areaZdM,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="供地面积(公顷)"
                    >
                        {form.getFieldDecorator('areaGdGq', {
                            rules: [{ required: true, message: '请输入供地面积(公顷)' }],
                            initialValue: townBer.areaGdGq,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="供地面积(亩)"
                    >
                        {form.getFieldDecorator('areaGdM', {
                            rules: [{ required: true, message: '请输入供地面积(亩)' }],
                            initialValue: townBer.areaGdM,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="土地用途"
                    >
                        {form.getFieldDecorator('tudiyongtu', {
                            rules: [{ required: true, message: '请输入土地用途' }],
                            initialValue: townBer.tudiyongtu,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="批准日期"
                    >
                        {form.getFieldDecorator('pizhunDate', {
                            rules: [{ required: true, message: '请选择批准日期' }],
                            initialValue: moment(townBer.pizhunDate, 'YYYY-MM-DD '),
                        })(
                            <DatePicker style={{ width: '100%' }} />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="盘活状态"
                    >
                        {form.getFieldDecorator('phZt', {
                            rules: [{ required: true }],
                            initialValue: townBer.phZt,
                        })(
                            <Select style={{ width: '100%' }}>
                                <Option value={0}>未开始</Option>
                                <Option value={1}>已开始</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="实景照片附件"
                    >
                        {form.getFieldDecorator('sjTupian')(
                            <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                headers={{ Authorization: sessionStorage.getItem('token') }}
                                showUploadList={false}
                                action={imgUpdate}
                                beforeUpload={beforeUpload}
                                onChange={indexUpdate}
                            >
                                {imageUrlBase ? <img src={imageUrlBase} alt="" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        )}
                    </FormItem>
                </Col>
            </Row>
        </Modal>
    );
});

const NewForm = Form.create()((props) => {
    const { modalVisible, form, handleAdd, handleModalVisible, loading, indexUpdate, imageUrlBase } = props;
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            if (typeof (fieldsValue.sjTupian) !== 'undefined') {
                if (typeof (fieldsValue.sjTupian.file.response) !== 'undefined') {
                    prime.sjTupian = fieldsValue.sjTupian.file.response.data.path;
                } else {
                    delete prime.sjTupian;
                }
            }
            handleAdd(prime);
        });
    };
    const canaleModal = () => {
        handleModalVisible();
        form.resetFields();
    };
    const uploadButton = (
        <div>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className="ant-upload-text">Upload</div>
        </div>
    );
    return (
        <Modal
            title="新增"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={canaleModal}
            width={1100}
        >
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={12} sm={24}>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="报备名称"
                    >
                        {form.getFieldDecorator('name', {
                            rules: [{ required: true, message: '请输入报备名称' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="建新区地块号"
                    >
                        {form.getFieldDecorator('jxqNumber', {
                            rules: [{ required: true, message: '请输入建新区地块号' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="土地坐落"
                    >
                        {form.getFieldDecorator('address', {
                            rules: [{ required: true, message: '请输入土地坐落' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="面积(公顷)"
                    >
                        {form.getFieldDecorator('areaGq', {
                            rules: [{ required: true, message: '请输入面积(公顷)' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="面积(亩)"
                    >
                        {form.getFieldDecorator('areaM', {
                            rules: [{ required: true, message: '请输入面积(亩)' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="征地面积(公顷)"
                    >
                        {form.getFieldDecorator('areaZdGq', {
                            rules: [{ required: true, message: '请输入征地面积(公顷)' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="备注"
                    >
                        {form.getFieldDecorator('remarks', {
                            rules: [{ required: true, message: '请输入备注' }],
                        })(
                            <TextArea placeholder="请输入" rows={4} />
                        )}
                    </FormItem>
                </Col>
                <Col md={12} sm={24}>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="征地面积(亩)"
                    >
                        {form.getFieldDecorator('areaZdM', {
                            rules: [{ required: true, message: '征地面积(亩)' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="供地面积(公顷)"
                    >
                        {form.getFieldDecorator('areaGdGq', {
                            rules: [{ required: true, message: '请输入供地面积(公顷)' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="供地面积(亩)"
                    >
                        {form.getFieldDecorator('areaGdM', {
                            rules: [{ required: true, message: '请输入供地面积(亩)' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="土地用途"
                    >
                        {form.getFieldDecorator('tudiyongtu', {
                            rules: [{ required: true, message: '请输入土地用途' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="批准日期"
                    >
                        {form.getFieldDecorator('pizhunDate', {
                            rules: [{ required: true, message: '请选择批准日期' }],
                        })(
                            <DatePicker style={{ width: '100%' }}/>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="盘活状态"
                    >
                        {form.getFieldDecorator('phZt', {
                            rules: [{ required: true }],
                            initialValue: 0,
                        })(
                            <Select style={{ width: '100%' }}>
                                <Option value={0}>未开始</Option>
                                <Option value={1}>已开始</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 11 }}
                        wrapperCol={{ span: 13 }}
                        label="实景照片附件"
                    >
                        {form.getFieldDecorator('sjTupian')(
                            <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                headers={{ Authorization: sessionStorage.getItem('token') }}
                                showUploadList={false}
                                action={imgUpdate}
                                beforeUpload={beforeUpload}
                                onChange={indexUpdate}
                            >
                                {imageUrlBase ? <img src={imageUrlBase} alt="" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        )}
                    </FormItem>
                </Col>
            </Row>
        </Modal>
    );
});
@connect(({ town, loading }) => ({
    town,
    loading: loading.models.town,
}))
@Form.create()
export default class town extends PureComponent {
    state = {
        loading: false,
        selectedRows: [],
        modalVisible: false,
        modalVisibleAdd: false,
        townBer: {},
        searchForm: {},
        imageUrlBase: '',
    };

    componentDidMount() {
        this.gainList(1, 10);
    }

    gainList = (page, size, data) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'town/fetch',
            payload: {
                page,
                size,
                data,
            },
        });
    }

    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
            imageUrlBase: '',
        });
    };

    townAdd = (flag) => {
        this.setState({
            modalVisibleAdd: !!flag,
            imageUrlBase: '',
        });
    };

    handleEdit = (fields, id) => {
        const parime = fields;
        const { dispatch } = this.props;
        dispatch({
            type: 'town/edit',
            payload: {
                ...parime,
                id,
            },
            callback: (data) => {
                information(data);
                this.gainList(this.props.town.town.page, this.props.town.town.size, this.state.searchForm);
            },
        });

        this.setState({
            modalVisible: false,
        });
    };

    handleAdd = (fields) => {
        const { form } = this.props;
        const parime = fields;
        const { dispatch } = this.props;
        dispatch({
            type: 'town/add',
            payload: {
                ...parime,
            },
            callback: (data) => {
                information(data);
                this.gainList(this.props.town.town.page, this.props.town.town.size, this.state.searchForm);
            },
        });

        this.setState({
            modalVisibleAdd: false,
        });
        form.resetFields();
    };

    townDel = (fields) => {
        const { dispatch, town: { town } } = this.props;
        confirm({
            title: '删除',
            content: '确认删除本条条目?',
            okType: 'danger',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: 'town/del',
                    payload: {
                        id: fields.id,
                    },
                    callback: (data) => {
                        information(data);
                        this.gainList(town.page, town.size, this.state.searchForm);
                    },
                });
            },
            onCancel() {
            },
        });
    }

    handleSelectRows = (rows) => {
        this.setState({
            selectedRows: rows,
        });
    };

    handleStandardTableChange = (pagination, filters, sorter) => {
        const data = { ...pagination.searchForm };
        this.gainList(pagination.current, pagination.pageSize, data);
    };

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({ searchForm: {} });
    };

    indexUpdate = ({ fileList, file }) => {
        const { status, response } = file;
        const { dispatch } = this.props;
        if (file.response && file.response.code !== 20000) {
            message.error(`${file.response.message},请重新登录`);
            dispatch({ type: 'login/logout' });
        }
        if (status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (status === 'done') {
            this.setState({
                loading: false,
                imageUrlBase: response.data.pathFull,
            });
        }
    }

    handleSearch = (e) => {
        e.preventDefault();

        const { dispatch, form } = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;
            if (fieldsValue.id && fieldsValue.id.toString().length > 10) {
                message.error('id小于等于10位');
                return;
            }
            this.setState({
                searchForm: { ...fieldsValue },
            });
            dispatch({
                type: 'town/fetch',
                payload: {
                    page: 1,
                    size: this.props.town.town.size,
                    data: {
                        ...fieldsValue,
                    },
                },
            });
        });
    };

    rendertownForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={8} sm={24}>
                        <FormItem label="报备名称">
                            {getFieldDecorator('name', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="建新区地块号">
                            {getFieldDecorator('jxqNumber', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="土地坐落">
                            {getFieldDecorator('address', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="面积(公顷)">
                            {getFieldDecorator('areaGq', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="面积(亩)">
                            {getFieldDecorator('areaM', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="征地面积(公顷)">
                            {getFieldDecorator('areaZdGq', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="征地面积(亩)">
                            {getFieldDecorator('areaZdM', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="供地面积(公顷)">
                            {getFieldDecorator('areaGdGq', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="盘活状态">
                            {getFieldDecorator('phZt', {
                                initialValue: 0,
                            })(
                                <Select style={{ width: '100%' }}>
                                    <Option value={0}>未开始</Option>
                                    <Option value={1}>已开始</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <span className={styles.submitButtons} style={{ textAlign: 'right' }}>
                            <Button icon="search" htmlType="submit">查询</Button>
                            <Button style={{ marginLeft: 8 }} type="dashed" onClick={this.handleFormReset}>重置</Button>
                            <Button style={{ marginLeft: 8 }} type="primary" onClick={this.townAdd}>新增</Button>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    render() {
        const { selectedRows, townBer, modalVisible, modalVisibleAdd, imageUrlBase } = this.state;
        const { town: { town }, loading, dispatch } = this.props;
        const parentMethods = {
            handleAdd: this.handleEdit,
            handleModalVisible: this.handleModalVisible,
            townBer,
            loading,
            imageUrlBase,
            indexUpdate: this.indexUpdate,
        };
        const Addtown = {
            loading,
            handleAdd: this.handleAdd,
            handleModalVisible: this.townAdd,
            indexUpdate: this.indexUpdate,
            imageUrlBase,
        };
        const columns = [
            {
                title: '报备名称',
                dataIndex: 'name',
            },
            {
                title: '建新区地块号',
                dataIndex: 'jxqNumber',
            },
            {
                title: '土地坐落',
                dataIndex: 'address',
            },
            {
                title: '面积(公顷)',
                dataIndex: 'areaGq',
            },
            {
                title: '面积(亩)',
                dataIndex: 'areaM',
            },
            {
                title: '征地面积(公顷)',
                dataIndex: 'areaZdGq',
            },
            {
                title: '征地面积(亩)',
                dataIndex: 'areaZdM',
            },
            {
                title: '供地面积(公顷)',
                dataIndex: 'areaGdGq',
            },
            {
                title: '供地面积(亩)',
                dataIndex: 'areaGdM',
            },
            {
                title: '土地用途',
                dataIndex: 'tudiyongtu',
            },
            {
                title: '批准日期',
                dataIndex: 'pizhunDate',
            },
            {
                title: '操作',
                render: (val, record) => (
                    <Fragment>
                        <ButtonGroup>
                            <Button type="ghost" onClick={() => {
                                this.handleModalVisible(true);
                                this.setState({
                                    townBer: record,
                                    imageUrlBase: record.sjTupian || '',
                                });
                            }}>编辑</Button>
                            <Button type="danger" onClick={() => {
                                this.townDel(record);
                            }}>删除</Button>
                        </ButtonGroup>
                    </Fragment>
                ),
            },
        ];

        return (
            <PageHeaderLayout title="城镇建新区">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.rendertownForm()}
                        </div>
                        <StandardTable
                            selectedRows={selectedRows}
                            loading={loading}
                            data={town}
                            columns={columns}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleStandardTableChange}
                            searchForm={this.state.searchForm}
                        />
                    </div>
                </Card>
                <CreateForm
                    {...parentMethods}
                    modalVisible={modalVisible}
                />
                <NewForm
                    {...Addtown}
                    modalVisible={modalVisibleAdd}
                />
            </PageHeaderLayout>
        );
    }
}
